//
//  InformationDetailsViewController.m
//  YXFinance
//
//  Created by uplooking on 2018/10/23.
//  Copyright © 2018年 CRLong. All rights reserved.
//

#import "InformationDetailsViewController.h"
#import <WebKit/WKWebViewConfiguration.h>

@interface InformationDetailsViewController ()
<
WKUIDelegate,
WKNavigationDelegate,
UITextFieldDelegate,
UITableViewDataSource,
UITableViewDelegate,
DZNEmptyDataSetDelegate,
DZNEmptyDataSetSource
>
{
    
    WKWebView * webView;
    CGFloat wkWebViewHeight;
    NewsIndexModel * indexModel;
    UIView * bomView;
    UITextField * pTextField;
    BOOL isKeyBorad;
    UITableView * tableView;
    NSMutableArray * arrayResult;
    BOOL isLoading;
    BOOL isCanLoadMore;
    ListLoadingFooterView *vListLoading;
    UIView *vListFooterNone;
    NSInteger page;
    NSInteger row;
    UIView * headerView;
    CGFloat  tHeight;
    
    BOOL isWebLoading;
    CGFloat sectionHeaderHeight;
    
}

@end

@implementation InformationDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBackLeftBarButtonItemAction:@selector(backAction:)];
    [self setBackRightBarButtonItemAction:@selector(shareAction:) image:[UIImage imageNamed:@"icon_fenxiang"]];
    
    isLoading = YES;
    row = 10;
    arrayResult=[NSMutableArray arrayWithCapacity:0];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];
    
    [self setBomView];
    [self startSKV];
    [self getNewsIndexDetailsData];
    [self getCommentListData];
}

-(void)endFullScreen{
    NSLog(@"退出全屏");
    [[UIApplication sharedApplication]setStatusBarHidden:NO animated:NO];
    
}

- (void)backAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)shareAction:(UIButton *)sender{
    
    [self setShareSDKImage:indexModel.litpic text:indexModel.intro title:indexModel.title url:[NSURL URLWithString:indexModel.source]];
    
}

- (void)initView{
    
    
    tHeight = [self heightByStringContent:indexModel.title andLabelWidth:kScreenWidth - 30 * kAutoScanleX andFontSize:18 * kAutoScanleX] + 6;
    
    headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 200 * kAutoScanleX)];
    
    UIView * titleView = [[UIView alloc]init];
    [headerView addSubview:titleView];
    [titleView setBackgroundColor:[UIColor whiteColor]];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView);
        make.left.equalTo(headerView);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(55 * kAutoScanleX + tHeight);
    }];
    
    
    UILabel * labelTitle = [[UILabel alloc]init];
    [labelTitle setText:indexModel.title];
    [labelTitle setTextColor:HexRGBA(0x000000, 1)];
    [labelTitle setFont:[UIFont systemFontOfSize:18 * kAutoScanleX]];
    [labelTitle setTextAlignment:NSTextAlignmentLeft];
    [labelTitle setNumberOfLines:0];
    [titleView addSubview:labelTitle];
    [labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(titleView).inset(15 * kAutoScanleX);
        make.height.mas_equalTo(tHeight);
    }];
    
    
    UILabel * labelTime = [[UILabel alloc]init];
    [labelTime setText:indexModel.addtime];
    [labelTime setTextColor:HexRGBA(0xa4a4a4, 1)];
    [labelTime setFont:[UIFont systemFontOfSize:12 * kAutoScanleX]];
    [labelTime setTextAlignment:NSTextAlignmentLeft];
    [titleView addSubview:labelTime];
    [labelTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labelTitle.mas_bottom).offset(10 * kAutoScanleX);
        make.left.equalTo(titleView).inset(15 * kAutoScanleX);
        make.height.mas_equalTo(15 * kAutoScanleX);
    }];
    
    UILabel * labelCount = [[UILabel alloc]init];
    [labelCount setText:[NSString stringWithFormat:@"%@次阅读",indexModel.views]];
    [labelCount setTextColor:HexRGBA(0xbc9a6d, 1)];
    [labelCount setFont:[UIFont systemFontOfSize:12 * kAutoScanleX]];
    [labelCount setTextAlignment:NSTextAlignmentLeft];
    [titleView addSubview:labelCount];
    [labelCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(labelTime);
        make.right.equalTo(titleView).offset(-15 * kAutoScanleX);
    }];
    
    
    
    UIView *line = [[UIView alloc]init];
    [line setBackgroundColor:HexRGBA(0xe9e9e9, 1)];
    [titleView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(titleView);
        make.left.right.equalTo(titleView).inset(15 * kAutoScanleX);
        make.height.mas_equalTo(0.5);
    }];
    
    
    webView = [[WKWebView alloc] init];
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:indexModel.body_url]];
    [webView loadRequest:request];
    [webView setUIDelegate:self];
    [webView setNavigationDelegate:self];
    webView.opaque = NO;
    webView.scrollView.scrollEnabled = NO;
    webView.scrollView.showsVerticalScrollIndicator = NO;
    [headerView addSubview:webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleView.mas_bottom);
        make.left.right.equalTo(headerView);
    }];
    
    UIView * midView = [[UIView alloc]init];
    [midView setBackgroundColor:HexRGBA(0xf5f5f5, 1)];
    [headerView addSubview:midView];
    [midView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(webView.mas_bottom);
        make.left.right.equalTo(webView);
        make.height.mas_equalTo(45 * kAutoScanleX);
    }];
    
    
    UIImageView * imageView = [[UIImageView alloc]init];
    [midView addSubview:imageView];
    [imageView setImage:[UIImage imageNamed:@"icon_quanbu_pinglun"]];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(midView);
        make.left.equalTo(midView).offset(15 * kAutoScanleX);
        make.size.mas_equalTo(CGSizeMake(6 * kAutoScanleX, 15 * kAutoScanleX));
    }];
    
    
    
    UILabel * clabel= [[UILabel alloc]init];
    [clabel setTextColor:HexRGBA(0x000000, 1)];
    [clabel setText:@"全部评论"];
    [clabel setFont:[UIFont systemFontOfSize:15 * kAutoScanleX]];
    [clabel setTextAlignment:NSTextAlignmentLeft];
    [midView addSubview:clabel];
    [clabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_right).offset(15 * kAutoScanleX);
        make.centerY.equalTo(midView);
    }];
    
    
    tableView = [[UITableView alloc] init];
    [tableView setBackgroundColor:[UIColor whiteColor]];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [tableView setShowsHorizontalScrollIndicator:NO];
    [tableView setShowsVerticalScrollIndicator:NO];
    [tableView setEmptyDataSetDelegate:self];
    [tableView setEmptyDataSetSource:self];
    tableView.mj_header = [ZNDIYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getCommentListData)];
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(bomView.mas_top);
    }];
    
    [tableView registerClass:[CommentIndexCell class] forCellReuseIdentifier:@"CommentIndexCell"];
    [tableView setTableHeaderView:headerView];
    
    
    vListFooterNone = [UIView new];
    [tableView setTableFooterView:vListFooterNone];
    vListLoading = [ListLoadingFooterView initLoadingFooter];
    
}

- (void)setBomView{
    
    bomView = [[UIView alloc]init];
    [bomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:bomView];
    [bomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.mas_equalTo(50 * kAutoScanleX);
    }];
    
    
    UIView *line = [[UIView alloc]init];
    [line setBackgroundColor:HexRGBA(0xcfd4db, 1)];
    [bomView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(bomView);
        make.height.mas_equalTo(0.5);
    }];
    
    UIView * leftView = [[UIView alloc]init];
    [leftView setBackgroundColor:HexRGBA(0xf5f5f5, 1)];
    [leftView.layer setMasksToBounds:YES];
    [leftView.layer setCornerRadius:33/2.0 * kAutoScanleX];
    [leftView.layer setBorderWidth:0.5];
    [leftView.layer setBorderColor:HexRGBA(0xaeaeae, 1).CGColor];
    [bomView addSubview:leftView];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bomView).offset(15 * kAutoScanleX);
        make.centerY.equalTo(bomView);
        make.size.mas_equalTo(CGSizeMake(522/2.0 * kAutoScanleX, 33 * kAutoScanleY));
    }];
    
    UIImageView * editImageView = [[UIImageView alloc]init];
    [leftView addSubview:editImageView];
    [editImageView setImage:[UIImage imageNamed:@"icon_pinglun"]];
    [editImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(leftView);
        make.left.equalTo(leftView).offset(15 * kAutoScanleX);
        make.size.mas_equalTo(CGSizeMake(16 * kAutoScanleX, 15 * kAutoScanleY));
    }];
    
    pTextField=[[UITextField alloc]init];
    [pTextField setDelegate:self];
    [leftView addSubview:pTextField];
    [pTextField setReturnKeyType:UIReturnKeyDone];
    [pTextField setFont:[UIFont systemFontOfSize:15 * kAutoScanleX]];
    [pTextField setValue:HexRGBA(0xaeaeae, 1) forKeyPath:@"_placeholderLabel.textColor"];
    [pTextField setPlaceholder:@"说点什么吧..."];
    [pTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(editImageView.mas_right).offset(5 * kAutoScanleX);
        make.centerY.equalTo(leftView);
        make.right.equalTo(leftView);
        make.height.mas_equalTo(30 * kAutoScanleY);
    }];
    
    
    UIButton * fBtn=[[UIButton alloc]init];
    [fBtn setBackgroundColor:HexRGBA(0xb99c6d, 1)];
    [fBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [fBtn addTarget:self action:@selector(fBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [fBtn setTitle:@"发表" forState:UIControlStateNormal];
    [fBtn.titleLabel setFont:[UIFont systemFontOfSize:16 * kAutoScanleX]];
    [fBtn.layer setMasksToBounds:YES];
    [fBtn.layer setCornerRadius:31/2.0 * kAutoScanleX];
    [bomView addSubview:fBtn];
    [fBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(leftView);
        make.right.equalTo(bomView).offset(-15 * kAutoScanleX);
        make.size.mas_equalTo(CGSizeMake(65 * kAutoScanleX, 31 * kAutoScanleX));
    }];
    
    
    
}

#pragma mark--tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger count = [arrayResult count];
    
    NSLog(@"%ld",count);
    
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WS(weakSelf);
    static NSString *identifier = @"CommentIndexCell";
    
    CommentIndexCell * cell = [_tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    
    CommentIndexModel * model = arrayResult[indexPath.row];
    [cell setIndexModel:model];
    
    [cell setBlockClickZan:^(CommentIndexModel * _Nonnull model) {
        [weakSelf setCommentInitWithModel:model];
    }];
    
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CommentIndexModel * model = arrayResult[indexPath.row];
    
    
    CGFloat height = [self heightByStringContent:model.msg andLabelWidth:kScreenWidth - 85 * kAutoScanleX andFontSize:14 * kAutoScanleX]+6;
    
    
    return height + 72 * kAutoScanleX;
}


#pragma mark -- 点赞
- (void)setCommentInitWithModel:(CommentIndexModel *)indexModel{
    
    WS(weakSelf);
    
    BOOL isLogin=[LoginCorrelationHelper loginCorrelationHelperIsLogin];
    [LoginCorrelationHelper shareInstance].loginFinishBlock=^{
        [weakSelf setCommentInitWithModel:indexModel];
    };
    
    if (!isLogin) return;
    
    
    [self showHudInView:self.view hint:@""];
    [HttpRequestHelper requestApiCommentOpt:@"good" comment_id:indexModel.c_id Block:^(NSString *msg) {
        [weakSelf hideHud];
        
        if (REQUEST_SUCCESS) {
            
            indexModel.is_goods = YES;
            indexModel.good = [@([indexModel.good integerValue] + 1) stringValue];
            
            [tableView reloadData];
            
        }else{
            
            [weakSelf showHint:msg];
        }
        
    }];
    
}

#pragma mark -- 发表
- (void)fBtnAction:(UIButton *)sender{
    
    WS(weakSelf);
    
    [self.view endEditing:YES];
    
    
    BOOL isLogin=[LoginCorrelationHelper loginCorrelationHelperIsLogin];
    [LoginCorrelationHelper shareInstance].loginFinishBlock=^{
        [weakSelf fBtnAction:sender];
    };
    
    if (!isLogin) return;
    
    
    NSString * msg = pTextField.text;
    
    if (msg.length == 0) {
        
        return [self showHint:@"请输入评论内容"];
    }
    
    [self showHudInView:self.view hint:@""];
    [HttpRequestHelper requestApiCommentAddMsg:msg news_id:_n_id Block:^(NSString *msg,NSString * infoMsg) {
        
        [weakSelf hideHud];
        
        if (REQUEST_SUCCESS) {
            
            [pTextField setText:@""];
            [self showHint:infoMsg];
            [weakSelf showHudInView:weakSelf.view hint:@""];
            [weakSelf getCommentListData];
            
        }else{
            
            [weakSelf showHint:msg];
        }
        
    }];
    
}

#pragma mark -- 评论列表
-(void)getCommentListData{
    
    page=0;
    
    [self getCommentListPageData];
    
}

-(void)getCommentListPageData{
    
    page ++;
    isLoading = YES;
    isCanLoadMore = NO;
    
    WS(weakSelf);
    [HttpRequestHelper requestApiCommentPage:page nums:row news_id:_n_id Block:^(NSString *msg, NSArray *array) {
        
        [tableView.mj_header endRefreshing];
        
        if (!isWebLoading) [weakSelf stopSKV];
        
        [weakSelf hideHud];
        isLoading = NO;
        
        if (page == 1 && [arrayResult count] != 0)
        {
            [arrayResult removeAllObjects];
            [tableView reloadData];
        }
        
        if (REQUEST_SUCCESS) {
            
            if ([array count]==row)
            {
                isCanLoadMore = YES;
                
                [tableView setTableFooterView:vListLoading];
            }else
            {
                [tableView setTableFooterView:vListFooterNone];
            }
            
            [arrayResult addObjectsFromArray:array];
            
            if (arrayResult.count == 0) {
                
                CommentIndexModel * model = [[CommentIndexModel alloc]init];
                model.msg = @"暂无评价";
                [arrayResult addObject:model];
            }
            
        }else{
            
            //            [weakSelf showHint:msg];
        }
        
        [tableView reloadData];
        
        
    }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    BOOL isReachBottom = tableView.contentOffset.y >= tableView.contentSize.height - tableView.bounds.size.height;
    
    if (isReachBottom && isCanLoadMore && !isLoading)
    {
        [self getCommentListPageData];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self setBackLeftBarButtonItemAction:@selector(backAction:)];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}


#pragma mark--弹起键盘
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = keyboardF.size.height;
    
    isKeyBorad = NO;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [bomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-height);
        }];
        
        [self.view layoutIfNeeded];
        
    }];
    
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    
    isKeyBorad = YES;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [bomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view);
        }];
        
        [self.view layoutIfNeeded];
        
    }];
    
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    if (! isKeyBorad) {
        
        [ApplicationDelegate.window endEditing:YES];
    }
    
}



#pragma mark ------ < WKUIDelegate,WKNavigationDelegate > ------
#pragma mark
/**  < 法2 >  */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    isWebLoading = NO;
    
    if (!isLoading) {
        
        [self stopSKV];
    }
    
    
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        CGFloat documentHeight = [result doubleValue];
        
        CGRect frame = headerView.frame;
        frame.size.height = tHeight + 100 * kAutoScanleX + documentHeight;
        headerView.frame = frame;
    
        [webView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(documentHeight);
        }];
        
        [tableView reloadData];
        
    }];
    
}


#pragma mark -- 获取数据
- (void)getNewsIndexDetailsData{
    
    WS(weakSelf);
    
    isWebLoading = YES;
    
    [HttpRequestHelper requestApiNewsDetailsId:_n_id Block:^(NSString *msg, NewsIndexModel *model) {
        
        [weakSelf stopSKV];
        
        if (REQUEST_SUCCESS) {
            
            indexModel = model;
            
            [weakSelf initView];
            [weakSelf startSKV];
            
        }else{
            
            [weakSelf showHint:msg];
        }
        
    }];
    
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.view endEditing:YES];
    
    return YES;
    
}



@end
